package com.zipking.cloud.springbootmybatis.util;

import org.apache.poi.ss.formula.functions.T;

import java.util.List;
import java.util.function.Function;

public class PaginationHelper<T> {
    private List<T> list;
    private int number;
    private int totalPages;
    private int totalItems;

    public PaginationHelper(List<T> list, int number, int totalItems) {
        this.list = list;
        this.number = number;
        this.totalItems = totalItems;
        this.totalPages = (int)Math.ceil((double)totalItems / (double)number);
    }

    public List<T> getList() {
        return list;
    }

    public int getNumber() {
        return number;
    }

    public int getTotalPages() {
        return totalPages;
    }

    public int getTotalItems() {
        return totalItems;
    }

    public static <T> PaginationHelper<T> create(List<T> list, int page, int size, Function<List<T>, Integer> countFunction) {
        int totalItems = countFunction.apply(list);
        int number = size;
        int totalPages = (int)Math.ceil((double)totalItems / (double)number);
        int start = (page - 1) * number;
        if (start >= list.size()) {
            start = 0;
        }
        if (start + number > list.size()) {
            number = list.size() - start;
        }
        return new PaginationHelper<>(list.subList(start, start + number), number, totalItems);
    }
}